const encoding = global.encoding; //字符编码工具类


//根据偏移量读取数据
//自动维护偏移量
class CursorBufferReader {
    constructor(buffer) {
        this._buffer = buffer;
        this._cursor = 0;
    }

    //读取一个uint32
    //小端读取
    readUint32() {
        const int32 = this._buffer.readUInt32LE(this._cursor);
        this._cursor += 4;
        return int32
    }

    //读取一个unint16(ushort)
    //小端
    readUint16(){
        const int16 = this._buffer.readUInt16LE(this._cursor);
        this._cursor += 2;
        return int16
    }

    //按byte读取字符 Latin1编码
    readLatin1(len) {
        const subBuffer = this._buffer.slice(this._cursor, this._cursor + len);
        this._cursor += len;
        return subBuffer.toString("latin1");
    }

    //按byte读取字符 韩语编码
    readCP949(len) {
        const subBuffer = this._buffer.slice(this._cursor, this._cursor + len);
        this._cursor += len;

        let buffer = encoding.convert(subBuffer, 'UTF-8', 'CP949')
        let str = buffer.toString();
        return str;
    }


    //读取指定字节的数据
    readBytes(len) {
        const subBuffer = this._buffer.slice(this._cursor, this._cursor + len);
        this._cursor += len;
        return subBuffer
    }

    //移动游标
    //@param offset:int 移动量
    //@param whence:int 从哪开始移动  0:从头 1:从当前位置 2文件末尾
    seek(offset, whence) {
        if (whence == 0) {
            if (offset > this._buffer.length) {
                console.error("CursorBufferReader.seek:超过了length最大值")
                return false;
            }
            return this._cursor = offset;
        }

        if (whence == 1) {
            if (this._cursor + offset > this._buffer.length) {
                console.error("CursorBufferReader.seek:超过了length最大值")
                return false;
            }
            return this._cursor += offset;
        }

        if (whence == 2) {
            if (this._buffer.length - offset < 0) {
                console.error("CursorBufferReader.seek:超过了length最大值")
                return false;
            }

            return this._cursor = this._buffer.length - offset
        }
    }

    //获取当前游标
    getCursor() {
        return this._cursor;
    }

    //获取剩余字节数量
    remaining() {
        return this._buffer.length - this._cursor;
    }

    //是否有剩余字节
    hasRemaining() {
        return this._cursor < this._buffer.length;
    }
}

module.exports = CursorBufferReader